//
//  DownloadTasksCtr.swift
//  soapp_Example
//
//  Created by zhuxietong on 2019/4/24.
//  Copyright © 2019 CocoaPods. All rights reserved.
//

import Foundation
import UIKit
import AsyncDisplayKit
import Eelay
extension FileRouter{
    var open_icon:UIImage?{
        get{
            switch self {
            case .audio,.video:
                return UIImage(named: "audio_play", in: Bundle(for: EeAudioPlayer.self), compatibleWith: nil)
            default:
                return nil
            }
        }
    }
}

open class DownloadView: JoView,DownloadObserver{
    open var task:Download.Task? = nil
    
    open var changeSelect:(NSMutableDictionary)->Void = {_ in}
    
    public static var showSelect = false{
        didSet{
            __post(notify: ToggleNotice.toggle)
        }
    }
    
    public static func toggleSelect(){
        DownloadView.showSelect = !DownloadView.showSelect
        __post(notify: ToggleNotice.toggle)
    }

    public enum ToggleNotice:String,NotifyType {
        
        case toggle = "toggle"
        
        public var name: Notification.Name{
            return "DownloadItemView.\(self.rawValue)".notice_name
        }
    }

    
    func setUpOpenBt() {
        guard let file = task?.file else {
            return
        }
        
        let router = FileRouter.type(url: file.locURL) ?? .unkown
        openIconV.image = router.open_icon
        startBtn.setTitle(nil, for: .normal)

    }
    
    open func updateDownloadStatus(_ status: Download.Status, task: Download.Task) {
        openIconV.image = nil
        switch status {
        case .failed(error:_):
            statusL.ui.font12.color(hex: "#991100").text("下载失败".loc)
            startBtn.ui.ncolor(color: .white).ntitle(title: "重试".loc)
        case .stoped:
            statusL.ui.font12.color(hex: "#888").text("已暂停".loc)
            startBtn.ui.ncolor(color: .white).ntitle(title: "继续下载".loc)
//            let display = (task.file.floatProgress.cg_floatValue * 100).print(num: 0)
//            startBtn.ui.ntitle(title: "\(display)%")

        case .processing(progress: let progress):
            let display = (progress.doubleValue.cg_floatValue * 100).print(num: 0)
            statusL.ui.font12.text(color: UIColor.main_color).text("下载中".loc)
            startBtn.ui.ncolor(color: .white).ntitle(title: "\(display)%")
            progressView.progress = task.file.floatProgress
        case .waiting:
            statusL.ui.font12.cl_666.right.text("等待下载".loc)
        case .success(code: _, message: _):
            fileSizeL.ui.font12.cl_666.text("\(task.file.m_size)")
            statusL.ui.font12.cl_333.text("已下载".loc)
            setUpOpenBt()
        }
    }
    
    public let progressView = UIProgressView()
    public let nameL = UILabel()
    public let createTimeL = UILabel()
    public let fileSizeL = UILabel()

    public let startBtn = UIButton()
    public let statusL = UILabel()
    public let editBt = UIButton()
    public let coverView = UIView()
    
    public let contentV = UIView()
    public let editView = UIView()
    
    public var leftConstrain = NSLayoutConstraint()
    public let deleteBt = UIButton()
    
    public let imgV = UIImageView()
    public let openIconV = UIImageView()
    public var willDeleteMark:Bool = false{
        didSet{
            mo.model[FK.selected] = willDeleteMark.tag
            changeSelect(mo.model)
        }
    }
    open override func addLayoutRules() {

        self.frame = [0,0,Swidth,80]
        contentV.eelay = [
            [coverView,[ee.L.Y,[12,0]],"60",90],
            [nameL,[coverView,ee.T.R,ee.T.L,[5,6]],[ee.R,-90]],
            [createTimeL,[coverView,ee.B.R,ee.B.L,[-5,6]],[ee.R,-100]],
            [fileSizeL,[createTimeL,ee.Y],[ee.R,-12]],
            [statusL,[nameL,ee.Y],[ee.R,-12]],
        ]
        coverView.backgroundColor = UIColor(shex: "f1f1f1")
        let aphalLayer = UIView()
        coverView.eelay = [
            [imgV,[ee.T.L.B.R]],
            [openIconV,[ee.X.Y],20,"20"],
            [aphalLayer,[ee.T.L.B.R]],
            [progressView,[ee.L.B.R],"4".+1000],
            [startBtn,[ee.X.Y]],
        ]
        aphalLayer.backgroundColor = UIColor(shex: "3333")
        coverView.bsui.set(radius: 0, width: 0.5, color: UIColor(shex: "#ccc"))
        nameL.numberOfLines = 2
        let editW = 50
        var left = 0
        if !DownloadView.showSelect
        {
            left = -editW
        }

       
        let lays:TP.lays = [
            [editView,[ee.L.T.B,[left.+1000,0,0]],editW],
            [contentV,[editView,ee.R,ee.L],[ee.T.B.R]]
        ]
        editView.eelay = [
            [deleteBt,[ee.X.Y,[4,0]]]
        ]
        
        let imgs = UIImage(named: "lc_radio_check_s", in: Bundle(for: CoInputController.self), compatibleWith: nil)?.rt_tintedImage(with: UIColor.main_color)
        let imgn = UIImage(named: "lc_radio_check_n", in: Bundle(for: CoInputController.self), compatibleWith: nil)?.rt_tintedImage(with: UIColor(shex: "#ccc"))

        deleteBt.ui.nimage(imgn).simage(imgs).padding(insets: [20])
        deleteBt.addTarget(self, action: #selector(selectToggle), for: .touchUpInside)
        leftConstrain =  self.setEeLays(lays: lays).1[0]
        
        progressView.trackTintColor = UIColor(shex: "#8888")
        progressView.progressTintColor = UIColor._tint
        startBtn.addTarget(self, action: #selector(toggle), for: .touchUpInside)
        startBtn.ui.ncolor(hex: "#fff").font(size: 11)
        
        weak var wself = self
        __notice.observer(ToggleNotice.toggle) { (type, notice) in
           wself?.updateToggle()
        }
    }
    
    @objc func selectToggle() {
        self.deleteBt.isSelected = !deleteBt.isSelected
        self.willDeleteMark = deleteBt.isSelected;
    }
    
    open func updateToggle() {
        
        UIView.beginAnimations(nil, context: nil)
        UIView.setAnimationDuration(0.1)
        UIView.setAnimationCurve(UIView.AnimationCurve.init(rawValue: 7)!)
        if DownloadView.showSelect{
            leftConstrain.constant = 0
        }else{
            leftConstrain.constant = -50
        }
        setNeedsLayout()
        setNeedsDisplay()
        layoutIfNeeded()
        UIView.commitAnimations()
    }
    
    @objc func toggle(){
        
        guard let _task = task else {
            return
        }
        let name = statusL.text ?? ""
    
        switch name {
        case "已暂停".loc,"等待下载".loc:
            _task.begin()
        case "下载中".loc:
            if !_task.islanch{
                _task.begin()
            }else{
                _task.canle()
            }
        case "已下载".loc:
            let file = _task.file
            let url = _task.file.locURL.appendURLQuery(["cover":file.cover,"name":file.cover])
            AppLink.open(url)
        case "下载失败".loc:
            task?.resumeData = nil;
            _task.begin()
            
        default:
            break
        }
//        switch _task.status {
//        case .stoped:
//            _task.begin()
//        case .waiting:
//            _task.begin()
//        case .processing(progress: _):
//            if !_task.islanch{
//                _task.begin()
//            }else{
//                _task.canle()
//            }
//        case .success(code: _, message: _):
//            let file = _task.file
////            print("=====LLLLL|\(_task.file.locURL)")
//            let url = _task.file.locURL.appendURLQuery(["cover":file.cover,"name":file.cover])
//            AppLink.open(url)
//        default:
//            break
//        }
    }
    
    

    override open func mo_model_reload() {
//        print("====|\(mo.model)")
        self.task = Download.default.getTask(url: mo.model["url",""])
//        print("task_id====|\(task?.ID)")
        deleteBt.isSelected = mo.model[FK.selected,""] == true.tag
        task?.add(observer: self)
        if let _task = task{
            mo.model["task"] = _task
            progressView.progress = _task.file.floatProgress
            nameL.ui.font12.cl_444.text(_task.file.name + "." + _task.file.dotName)
            imgV.img_url = _task.file.cover
            createTimeL.attributedText = _task.file.createDate["yyyy-MM-dd"].ui.font10.cl_888.astring
        }
    }
    
    deinit {
//        print("+-------------------------------------------------\(self.task)")
//        self.task?.remove(observer: self)
    }
    
}


class DowloadCell: ASSizeRangeCell {
    
    var node = ASDisplayNode { () -> UIView in
        let itemView = DownloadView(frame: [0,0,Swidth,80])
        return itemView
    }
    
    var itemView:DownloadView?{
        get{
            return node.view as? DownloadView
        }
    }
    
    override func addLayoutRules() {
        separatorColor = UIColor.separator_color
        separatorHeight = TP.separatorHeight
    }
    
    override func mo_model_reload() {
        weak var wself = self
        itemView?.changeSelect = {
            obj in
            wself?.active(ID: "changeSelect")
        }
        itemView?.mo.model = mo.model
    }
    
    override func specGetter() -> _Spec {
        return .center([], xy: .xy, child: node["80",Swidth])
    }
    
    override func sizeRange() -> ASSizeRange {
        return ASSizeRange(min: CGSize(width: Swidth, height: 81), max: CGSize(width: Swidth, height: 81))
    }
    
    deinit {

    }
}




open class DownloadTasksCtr: ASColListController {
    
    
    public var isTest = true
    open override func touch(cell: Any, actionID: String, model: NSMutableDictionary) {
        if actionID  == "changeSelect"{
            bar.updateStatus()
        }
    }
    
    open var sections:TP.section{
        get{
            
//            let sec:TP.section = [
//                [
//                    ["url":"http://test.doncheng.cn/public/attachment/video/20190228/9184c60644692aeba61bebdd77fdd9a2.mp4"],
//                ],
//            ]
//            return sec
            
            let onesec = Download.fileSection
            
//            print("==========++OOO|\(onesec)")
                let sec:TP.section = [
                    onesec
                ]
                if onesec.count < 1{
                    self.mo_request_alert(msg: "没有下载项".loc, title: "", bt_title: "")
                    if isTest{
                        self.navigationItem.rightBarButtonItems = [
                            UIBarButtonItem(title: "clear", style: .done, target: self, action: #selector(clear)),
                            UIBarButtonItem(title: "add", style: .done, target: self, action: #selector(add)),
                            UIBarButtonItem(title: "toggle", style: .done, target: self, action: #selector(toggle)),
                        ]
                    }else{
                        self.navigationItem.rightBarButtonItem = nil
                    }
                        
                }
                else{
                    self.loadingV.dismiss()
                    if isTest{
                        self.navigationItem.rightBarButtonItems = [
                            UIBarButtonItem(title: "clear", style: .done, target: self, action: #selector(clear)),
                            UIBarButtonItem(title: "add", style: .done, target: self, action: #selector(add)),
                            UIBarButtonItem(title: "toggle", style: .done, target: self, action: #selector(toggle)),
                        ]
                    }else{
                        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "编辑".loc, style: .done, target: self, action: #selector(toggle))
                        
                    }
                }
            
                return sec
        }
    }
    
    open var selector:TP.selector{
        get{
            let sel:TP.selector = [
                "<default>":DowloadCell.self,
            ]
            return sel
        }
    }
    
    
    
    
    
    open override func mo_model_reload() {
        //        self.__link = Jifen.path.appendURLQuery(["id":ID])
        //        EeURLCreator(path: Jifen.path, params: ["id":ID]).rawUrl
    }
    
    public static var Link = "download/files"
    
    
    open override func viewDidLoad() {
        super.viewDidLoad()
        self.__link = DownloadTasksCtr.Link;

        
        DownloadView.showSelect = false
        title = "我的下载".loc
        updateData()
        let resetBt = UIButton()
        resetBt.addTarget(self, action: #selector(clear), for: .touchUpInside)
        
       
      
        
        weak var wself = self
        __notice.observer(DownloadView.ToggleNotice.toggle) { (type, notice) in
            wself?.toggleBottom()
        }
    }
    
    func updateData() {
        collectionNode.load(sections: sections, selector: selector)
        collectionNode.reloadData()
    }
    
    @objc open func toggleBottom() {

        UIView.beginAnimations(nil, context: nil)
        UIView.setAnimationDuration(0.1)
        UIView.setAnimationCurve(UIView.AnimationCurve.init(rawValue: 7)!)
        if !DownloadView.showSelect{
            self.bottomConstrain.constant = bar.frame.height
        }else{
            self.bottomConstrain.constant = 0
        }
        jo_contentView.setNeedsLayout()
        jo_contentView.setNeedsDisplay()
        jo_contentView.layoutIfNeeded()
        UIView.commitAnimations()
    }
    
    
    let bar = BottomView()
    var bottomConstrain = NSLayoutConstraint()
    override open func layCollection(collectionView: UIView) {
        let lays:TP.lays = [
            [bar,[ee.B.L.R,[100,0,0]]],
            [collectionView,[ee.T.L.R],[bar,ee.T,ee.B]],
        ]
        bottomConstrain = jo_contentView.setEeLays(lays: lays).1[0]
        bar.controller = self
        bar.node = collectionNode
        
    }
    
    @objc open func toggle(){
        DownloadView.toggleSelect()
    }
    
    @objc open func clear(){
        DownFileManager.removeAllFileAndCache()
        collectionNode.load(sections: sections, selector: selector)
        collectionNode.reloadData()
    }
    
    public var index = 0
    @objc open func add(){
        var url = "http://test.doncheng.cn/public/attachment/video/20190221/b773cf27af9ac674f016e634c41d4e29.mp4"
        if index%3 == 0{
            url = "http://test.doncheng.cn/public/attachment/video/20190221/b773cf27af9ac674f016e634c41d4e29.mp4"
        }
        if index%3 == 1{
            url = "http://test.doncheng.cn/public/attachment/audio/20190416/191bfb6d4cc7b3224f7ab5803013aa99.mp3"
        }
        if index%3 == 2{
            url = "http://test.doncheng.cn/public/attachment/video/20190317/82ee201bfba8b1dfe5529d71a83218a4.mp4"
        }
        index = index + 1
        
        let info = Download.default.addTask(url: url,fileName: "MV小电影\(index)",cover: "http://a.hiphotos.baidu.com/image/pic/item/30adcbef76094b36d4bfddfea9cc7cd98d109df0.jpg")
        if info.isExist{
            "\(info.task!.file.name) 已在下载".loc.alert()
            info.task?.begin()
        }else{
            info.task?.begin()
            collectionNode.load(sections: sections, selector: selector)
            collectionNode.reloadData()
            bar.updateStatus()
        }
    }
    
    
    
    
    
    deinit {
//        print("+==sss====DownloadTasksCtr")

    }

    
}


extension DownloadTasksCtr{
    open class BottomView: EeBottomBar {
        override open var contentHeight: CGFloat{
            return 50
        }
        
        let leftBt = UIButton()
        let rightBt = UIButton()
        
        var tasks = [(Int,Download.Task)]()
        
        
        public weak var node:ASCollectionNode? = nil
        
        public func updateStatus(){
            
            let list = DataNode.path(node: "section0", node?.model, value: NSMutableArray())
            var tasks = [(Int,Download.Task)]()
            list.list { (obj:NSMutableDictionary, i) in
                if obj[FK.selected,""] == true.tag
                {
                    if let t = obj.object(forKey: "task") as? Download.Task{
                        tasks.append((i,t))
                    }
                }
            }
            if tasks.count >= list.count{
                leftBt.isSelected = true
            }
            else{
                leftBt.isSelected = false
            }
            if list.count < 1{
                leftBt.isSelected = true

            }
            if tasks.count > 0{
                rightBt.ui.ncolor(color: UIColor.main_color).ntitle(title: "\("删除".loc)(\(tasks.count))")
                rightBt.isEnabled = true
            }
            else{
                rightBt.ui.ncolor(hex: "#999").ntitle(title: "删除".loc)
                rightBt.isEnabled = false
            }
            self.tasks = tasks
        }
        
        open override func addLayoutRules() {
            let blurView = UIVisualEffectView()
            let sty = UIBlurEffect.Style.extraLight
            let blurEffect = UIBlurEffect(style: sty)
            blurView.effect = blurEffect
            
            self.eelay = [
                [blurView,[ee.T.L.B.R]]
            ]
            
            backgroundColor = .clear
            let centerLine = UIView()
            contentView.eelay = [
                [leftBt,[ee.L.X.Y,ee.L.R.Y]],
                [rightBt,[ee.R.X.Y,ee.R.L.Y]],
                [centerLine,[ee.X.Y],"26",1],
            ]
            centerLine.backgroundColor = UIColor(shex: "#cccc")
            
            //            backgroundColor = UIColor(shex: "#f1f1f1")
            leftBt.ui.font(size: 13).ncolor(hex: AppTheme.main_hex).ntitle(title: "全选".loc).stitle(title: "取消全选".loc)
            rightBt.ui.font(size: 13).ncolor(hex: AppTheme.main_hex).ntitle(title: "删除".loc)
            rightBt.isEnabled = false
            rightBt.addTarget(self, action: #selector(deleleAction), for: .touchUpInside)
            leftBt.addTarget(self, action: #selector(selectAllAction), for: .touchUpInside)
            
        }
        
        @objc open func deleleAction(){
            var indexPs = [IndexPath]()
//            print("+++++D|\(tasks)")
            let list = DataNode.path(node: "section0", node?.model, value: NSMutableArray())
//            print("++++++++|\(list)")
            if self.tasks.count < 1{
                "请选择要删除的内容".loc.alert()
            }else{
                var objs = [NSMutableDictionary]()
                for one in tasks{
                    one.1.delete()
                    objs.append(list[one.0] as!NSMutableDictionary)
                    indexPs.append(IndexPath(item: one.0, section: 0))
                }
                for dict in objs{
                    list.remove(dict)
                }
            }
//            print("++++++|\(indexPs)")
            node?.deleteItems(at: indexPs)
            self.updateStatus()
            
        }
        
        @objc open func selectAllAction(){
            if leftBt.isSelected{
                let list = DataNode.path(node: "section0", node?.model, value: NSMutableArray())
                list.list { (obj:NSMutableDictionary, i) in
                    obj[FK.selected] = false.tag
                }
                node?.reloadData()
                self.updateStatus()
            }
            else{
                let list = DataNode.path(node: "section0", node?.model, value: NSMutableArray())
                list.list { (obj:NSMutableDictionary, i) in
                    obj[FK.selected] = true.tag
                }
                node?.reloadData()
                self.updateStatus()
            }
            
        }
    }
}
